package org.whatever.aha.zjut.platform.controller.academy;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.whatever.aha.zjut.base.constant.AuthConst;
import org.whatever.aha.zjut.base.constant.ErrorCode;
import org.whatever.aha.zjut.base.constant.MsgTypeRedisConstant;
import org.whatever.aha.zjut.base.constant.StatusConstant;
import org.whatever.aha.zjut.base.dto.AjaxResult;
import org.whatever.aha.zjut.base.exception.AppException;
import org.whatever.aha.zjut.platform.annotation.CheckAcademyAdminModifyProject;
import org.whatever.aha.zjut.platform.entity.competition.AcademyCompetition;
import org.whatever.aha.zjut.platform.entity.project.Project;
import org.whatever.aha.zjut.platform.message.MessageService;
import org.whatever.aha.zjut.platform.service.AcademyAdminService;
import org.whatever.aha.zjut.platform.service.UserService;
import org.whatever.aha.zjut.platform.service.competition.AcademyCompetitionService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionStageStatusService;
import org.whatever.aha.zjut.platform.service.project.ProjectService;
import org.whatever.aha.zjut.platform.vo.academy.HistoryVo;
import org.whatever.aha.zjut.platform.vo.academy.RecommendVo;
import org.whatever.aha.zjut.platform.vo.competition.AcademyCompetitionVo;
import org.whatever.aha.zjut.platform.vo.project.ProjectDetailVo;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * @author Vc
 * @version 1.0
 * @Desc
 * @date 2021/10/30 17:24
 */
@Api(tags = "院级管理员-审核项目相关操作类")
@RequestMapping("/v1/academy/judge")
@RequiredArgsConstructor
@RestController
@Validated
@SaCheckRole(value = {AuthConst.R_supper, AuthConst.R_academy}, mode = SaMode.OR)
public class AcademyJudgeController {
    final AcademyCompetitionService academyCompetitionService;
    final ProjectService projectService;
    final AcademyAdminService academyAdminService;
    final CompetitionStageStatusService competitionStageStatusService;
    final MessageService messageService;
    final UserService userService;

    @ApiOperation("获得审核项目中统计数据")
    @GetMapping("/getStatistics/{compId}/{stageId}")
    AjaxResult<Map> getStatistics(@PathVariable("compId")int compId,
                                  @PathVariable("stageId")int stageId){
        int userId = StpUtil.getLoginIdAsInt();
        int academyId = academyAdminService.getAcademyIdByUserId(userId);
        int total = projectService.getProjectNumByAcademyIdAndStatus(academyId, null, compId, stageId, null);
        int alreadyRec = projectService.getProjectNumByAcademyIdAndStatus(academyId, StatusConstant.PROJECT_ALREADY_SUPPOSE_SUBMIT.getCode(), compId, stageId, null);
        int alreadyCheck = projectService.getAcademyAlreadyCheckNum(stageId, academyId);
        AcademyCompetitionVo academyCompetitionVo = academyCompetitionService.getAcademyCompetitionVoById(academyId, stageId);
        return AjaxResult.SUCCESS(Map.of("alreadyCheck",alreadyCheck,"alreadyRec",alreadyRec,"total",total, "academyCompetitionVo", academyCompetitionVo));
    }


    @CheckAcademyAdminModifyProject
    @ApiOperation("退回修改给学生")
    @PutMapping("/returnForModify/{projectId}")
    @Transactional(rollbackFor = Exception.class, propagation= Propagation.REQUIRED)
    AjaxResult<Integer>  returnForModify(@PathVariable("projectId")int projectId,
                                         @RequestBody String comment){
        Project project = projectService.getProjectById(projectId);
        if(StatusConstant.PROJECT_IS_SCHOOL_COMMUNITY_REC.getCode().equals(project.getProjectSchoolRec() ? 1 : 0) ||
                StatusConstant.PROJECT_ALREADY_SUPPOSE_SUBMIT.getCode().equals(project.getProjectSupposeSubmit() ? 1 : 0) ||
                    StatusConstant.PROJECT_AWARD_THIRD_PRIZE.getCode().equals(project.getProjectAwardId())){
            throw new AppException(ErrorCode.ACADEMY_RETURN_FOR_MODIFY_NOT_QUALIFY);
        }
        int userId = StpUtil.getLoginIdAsInt();
        int affectRow = projectService.academyReturnForModify(projectId, comment, userId);
        SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sendTime = s.format(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
        messageService.createUserMessage(StatusConstant.MSG_SYS_SENDER.getCode(), project.getProjectLeaderId(), sendTime,
                MsgTypeRedisConstant.MSG_TYPE_PROJECT_RETURN_TITLE, MsgTypeRedisConstant.getKeyProjectReturn(project.getProjectName(), "院级管理员", comment),
                MsgTypeRedisConstant.MSG_SYS_NAME, StatusConstant.MSG_TYPE_PROJECT_RETURN.getCode());
        return AjaxResult.SUCCESS(affectRow);
    }

    @ApiOperation("获取所有未推荐项目，未审核排先")
    @GetMapping("/getUnrecProjects/{compId}/{stageId}")
    AjaxResult<List<RecommendVo>> getUnrecProjects(@PathVariable("compId")int compId,
                                                   @PathVariable("stageId")int stageId){
        int userId = StpUtil.getLoginIdAsInt();
        return AjaxResult.SUCCESS(academyAdminService.getUnrecProjects(academyAdminService.getAcademyIdByUserId(userId), compId, stageId));
    }

    @ApiOperation("获取已推荐普通项目")
    @GetMapping("/getNormalProjects/{compId}/{stageId}")
    AjaxResult<List<RecommendVo>> getNormalProjects(@PathVariable("compId")int compId,
                                                    @PathVariable("stageId")int stageId){
        int userId = StpUtil.getLoginIdAsInt();
        return AjaxResult.SUCCESS(academyAdminService.getNormalProjects(academyAdminService.getAcademyIdByUserId(userId), compId, stageId));
    }

    @ApiOperation("获取院级自评三等奖项目")
    @GetMapping("/getAcademyThirdPrizeProjects/{compId}/{stageId}")
    AjaxResult<List<RecommendVo>> getAcademyThirdPrizeProjects(@PathVariable("compId")int compId,
                                                               @PathVariable("stageId")int stageId){
        int userId = StpUtil.getLoginIdAsInt();
        return AjaxResult.SUCCESS(academyAdminService.getAcademyThirdPrizeProjects(academyAdminService.getAcademyIdByUserId(userId), compId, stageId));
    }

    @ApiOperation("获取省级推荐项目")
    @GetMapping("/getProvinceRecProjects/{compId}/{stageId}")
    AjaxResult<List<RecommendVo>> getProvinceRecProjects(@PathVariable("compId")int compId,
                                                         @PathVariable("stageId")int stageId){
        int userId = StpUtil.getLoginIdAsInt();
        return AjaxResult.SUCCESS(academyAdminService.getProvinceRecProjects(academyAdminService.getAcademyIdByUserId(userId), compId, stageId));
    }

    @ApiOperation("获取校团委推荐项目")
    @GetMapping("/getSchoolRecProjectInfo/{compId}/{stageId}")
    public AjaxResult<List<RecommendVo>> getSchoolCommunityRecProjectInfo(@PathVariable(value = "compId") int compId,
                                                            @PathVariable("stageId")int stageId){
        int userId = StpUtil.getLoginIdAsInt();
        return AjaxResult.SUCCESS(academyAdminService.getSchoolCommunityRecProjectInfo(academyAdminService.getAcademyIdByUserId(userId), compId, stageId));
    }

    @CheckAcademyAdminModifyProject
    @ApiOperation("取消推荐")
    @PutMapping("/cancelRec/{projectId}")
    AjaxResult<Integer> cancelRec(@PathVariable("projectId")int projectId){
        Project project = projectService.getProjectById(projectId);
        if (StatusConstant.PROJECT_IS_SCHOOL_COMMUNITY_REC.getCode().equals(project.getProjectSchoolRec() ? 1 : 0)){
//        if(project.getProjectSchoolRec().equals(StatusConstant.PROJECT_IS_SCHOOL_COMMUNITY_REC.getCode() == 1)){
            // 校团委推荐项目不可操作
            throw new AppException(ErrorCode.OPERATION_NOT_AUTHORIZED);
        }
        return AjaxResult.SUCCESS(academyAdminService.cancelRec(projectId));
    }

    @CheckAcademyAdminModifyProject
    @ApiOperation("普通推荐项目")
    @PutMapping("/normalRecProject/{projectId}")
    AjaxResult<Integer> normalRecProject(@PathVariable("projectId")int projectId){
        int userId = StpUtil.getLoginIdAsInt();
        Project project = projectService.getProjectById(projectId);

        if(StatusConstant.PROJECT_IS_SCHOOL_COMMUNITY_REC.getCode().equals(project.getProjectSchoolRec() ? 1 : 0)){
//        if(project.getProjectSchoolRec().equals(StatusConstant.PROJECT_IS_SCHOOL_COMMUNITY_REC.getCode() == 1)){
            // 校团委推荐项目不可操作
            throw new AppException(ErrorCode.OPERATION_NOT_AUTHORIZED);
        }
        if(StatusConstant.PROJECT_IS_SCHOOL_COMMUNITY_REC.getCode().equals(project.getProjectSchoolRec() ? 1 : 0) ||
                StatusConstant.PROJECT_IS_PROVINCE_REC.getCode().equals(project.getProjectProvinceRec() ? 1 : 0)){
            throw new AppException(ErrorCode.ACADEMY_REC_TYPE_ERROR_CODE);
        }
        int userAcademyId = academyAdminService.getAcademyIdByUserId(userId);
        //推荐数目小于可推荐数量
        int alreadyRec = projectService.getProjectNumByAcademyIdAndStatus(userAcademyId, StatusConstant.PROJECT_ALREADY_SUPPOSE_SUBMIT.getCode(), project.getCompId(), project.getStageId(), true);
        if(alreadyRec >= academyCompetitionService.getAcademyCompetitionById(userAcademyId, project.getStageId()).getAcademyRecAmt()){
            throw new AppException(ErrorCode.ACADEMY_REC_AMT_EXCEED);
        }

        return AjaxResult.SUCCESS(academyAdminService.normalRecProject(projectId));
    }

    @CheckAcademyAdminModifyProject
    @ApiOperation("推荐省级")
    @PutMapping("/recProvinceProject/{projectId}")
    AjaxResult<Integer> recProvinceProject(@PathVariable("projectId")int projectId){
        int userId = StpUtil.getLoginIdAsInt();
        ProjectDetailVo projectDetailVo = projectService.getProjectDetailById(projectId);
        System.out.println(projectDetailVo.getProjectProvinceRec());
        if(StatusConstant.PROJECT_IS_PROVINCE_REC.getCode().equals(projectDetailVo.getProjectProvinceRec() ? 1 : 0)){
            throw new AppException(ErrorCode.ACADEMY_REC_TYPE_ERROR_CODE);
        }
        int userAcademyId = academyAdminService.getAcademyIdByUserId(userId);
        //省级推荐数目小于省级可推荐数量
        int provinceAlreadyRec = projectService.getProvinceProjectNum(projectDetailVo.getStageId(), userAcademyId);
        if(provinceAlreadyRec >= academyCompetitionService.getAcademyCompetitionById(userAcademyId, projectDetailVo.getStageId()).getAcademyProvinceRecAmt()){
            throw new AppException(ErrorCode.ACADEMY_REC_AMT_EXCEED);
        }
        return AjaxResult.SUCCESS(academyAdminService.recProvinceProject(projectId));
    }

    @CheckAcademyAdminModifyProject
    @ApiOperation("自评三等奖")
    @PutMapping("/academyThirdPrizeProject/{projectId}")
    AjaxResult<Integer> academyThirdPrizeProject(@PathVariable("projectId")int projectId){
        int userId = StpUtil.getLoginIdAsInt();
//        //确认用户拥有项目修改权限  (同一个学院 + 学校状态为 1：不可见 + 提交和审核阶段)
        ProjectDetailVo projectDetailVo = projectService.getProjectDetailById(projectId);
        int userAcademyId = academyAdminService.getAcademyIdByUserId(userId);
//        int projectAcademyId = projectService.getProjectDetailById(projectId).getAcademyId();
//        int projectSchoolRec = projectDetailVo.getProjectSchoolRec() == true ? 1 : 0;
//        CompetitionStageStatus SubmitCompStageStatus = competitionStageStatusService.getSingleCompStageStatus(projectDetailVo.getStageId(),  StatusConstant.COMPETITION_STAGE_STATUS_ORDER_SUBMIT.getCode());
//        CompetitionStageStatus JudgeCompStageStatus = competitionStageStatusService.getSingleCompStageStatus(projectDetailVo.getStageId(),  StatusConstant.COMPETITION_STAGE_STATUS_ORDER_JUDGE.getCode());
//        CheckUtil.checkAcademyAdminModifyProjectPermission(userAcademyId, projectAcademyId, projectSchoolRec, SubmitCompStageStatus.getStatusStartTime(), JudgeCompStageStatus.getStatusEndTime());
        //自评三等奖推荐数目小于自评三等奖可推荐数量
        int provinceAlreadyRec = projectService.getAcademyThirdPrizeProjectNum(projectDetailVo.getStageId(), userAcademyId);
        if(provinceAlreadyRec >= academyCompetitionService.getAcademyCompetitionById(userAcademyId, projectDetailVo.getStageId()).getThirdPrizeAmt()){
            throw new AppException(ErrorCode.ACADEMY_REC_AMT_EXCEED);
        }
        return AjaxResult.SUCCESS(academyAdminService.academyThirdPrizeProject(projectId));
    }

    @CheckAcademyAdminModifyProject
    @ApiOperation("批量提交已推荐项目")
    @PutMapping("/batchSubmit/{compId}")
    AjaxResult<Integer> batchSubmit(@PathVariable("compId")int compId) {
        int userId = StpUtil.getLoginIdAsInt();
        int userAcademyId = academyAdminService.getAcademyIdByUserId(userId);
        List<Project> alreadyRecProjects = projectService.getAlreadyRecProjects(userAcademyId, compId);
        //无项目可提交
        if (alreadyRecProjects.isEmpty()) {
            throw new AppException(ErrorCode.ACADEMY_HAS_NO_PROJECT_TO_SUBMIT);
        }
        //把校级管理员视角置为 2:未审核
        alreadyRecProjects.forEach(project -> {
            project.setProjectSchoolStatus(StatusConstant.PROJECT_STATUS_SCHOOL_VERSION_WAIT_FOR_JUDGE.getCode());
            projectService.updateProject(project);
        });
        ProjectDetailVo projectDetailVo = projectService.getProjectDetailById(alreadyRecProjects.get(0).getProjectId());
        //学院信息提交状态（0：未提交 1：已提交）改为已提交
        AcademyCompetition academyCompetition = academyCompetitionService.getAcademyCompetitionById(userAcademyId, projectDetailVo.getStageId());
        academyCompetition.setSubmitStatus(StatusConstant.PROJECT_ALREADY_SUBMIT.getCode() == 1);
        academyCompetitionService.updateAcademyCompetition(academyCompetition);
        return AjaxResult.SUCCESS(alreadyRecProjects.size());
    }

    @ApiOperation("根据比赛年份与赛事类型、学院Id获取学院赛事结果")
    @GetMapping("/getHistory")
    AjaxResult<List<HistoryVo>> getHistory(@RequestParam(value = "compYear", required = true) int compYear,
                                           @RequestParam(value = "compType", required = true) int compType,
                                           @RequestParam(value = "stageId", required = true) int stageId){
        int userId = StpUtil.getLoginIdAsInt();
        int academyId = academyAdminService.getAcademyIdByUserId(userId);
        return AjaxResult.SUCCESS(academyAdminService.getHistory(compYear, compType, academyId, stageId));
    }

    @CheckAcademyAdminModifyProject
    @ApiOperation("已审核接口")
    @PutMapping("/judgeProject/{projectId}")
    AjaxResult<Integer> judgeProject(@PathVariable("projectId")int projectId){
        return AjaxResult.SUCCESS(academyAdminService.judgeProject(projectId));
    }

    @CheckAcademyAdminModifyProject
    @ApiOperation("添加备注")
    @PutMapping("/addNote/{projectId}")
    AjaxResult<Integer> addNote(@PathVariable("projectId")int projectId, @RequestParam(value = "note", required = true)String note){
        return AjaxResult.SUCCESS(academyAdminService.addNote(projectId, note));
    }

    @ApiOperation("获得备注")
    @GetMapping("/getNote/{projectId}")
    AjaxResult<String> getNote(@PathVariable("projectId")int projectId){
        return AjaxResult.SUCCESS(academyAdminService.getNote(projectId));
    }

}
